#!/usr/bin/python -u

import sys
import time
import os
import re

def FileReplace(filename, dirname = None):
    tok = filename.split('.')
    ext = tok[len(tok) - 1]
    if ext != 'h' and ext != 'cpp':
        return
    if dirname != None:
        filename = dirname + filename
    print "Now Formating " + filename
    sys.stdout.flush()
    try:
        fp = open(filename, 'rw+')
    except:
        print "open" + filename + "error!"

    contents = fp.readlines()
    fp.seek(0, 0)
    for eachline in contents:
        cnt = 0
        for c in eachline:
            if c != '\t':
                fp.write(c)
                cnt = (cnt + 1) % 4
                continue
            for i in range(0, 4 - cnt):
                fp.write(' ')
            cnt = 0
    
    fp.close()

def DirReplace(dirname):
    filelist = os.listdir(dirname)
    print filelist
    for eachFile in filelist:
        if os.path.isdir(eachFile):
            newdir = dirname + '/' + eachFile
            print "Go to the dir: " + newdir
            sys.stdout.flush()
            DirReplace(newdir)
#time.sleep(1)
        else:
            FileReplace(eachFile, dirname)
#time.sleep(1)

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print "usage %s filename or dirname" %sys.argv[0]
        exit()
    filename = sys.argv[1]
    if os.path.isdir(filename):
        DirReplace(filename)
    else:
        FileReplace(filename)
